package com.jl.bean;

import com.util.EncodingUtil;

public class CMD_55AA {

	private static final String STX = "55AA";
	private String RSCTL = "00";
	private String LEN = "0000";
	private String CMD = "00";
	private String DATA = "";
	private String BCC = "00";
	private String CMDSTR = "";

	private static int rsctl = 0;

	private CMD_55AA() {}

	/**
	 *
	 * @param CMD
	 * @param DATA
	 * @return
	 */
	public static CMD_55AA create(String CMD, String DATA) {
		if (CMD == null || DATA.length() % 2 == 1)
			return null;
		CMD_55AA cmd = new CMD_55AA();
		cmd.RSCTL = "0" + rsctl;

		cmd.CMD = CMD.toUpperCase();
		cmd.DATA = DATA.toUpperCase();
		cmd.LEN = ("0000" + Integer.toHexString(cmd.DATA.length() / 2));
		cmd.LEN = cmd.LEN.substring(cmd.LEN.length() - 4, cmd.LEN.length());
		cmd.BCC = EncodingUtil.yihuo(EncodingUtil.change(cmd.RSCTL + cmd.LEN
				+ cmd.CMD + cmd.DATA));
		cmd.CMDSTR = STX + cmd.RSCTL + cmd.LEN + cmd.CMD + cmd.DATA + cmd.BCC;

		if (rsctl >= 7) {
			rsctl = 0;
		} else {
			rsctl++;
		}
		return cmd;
	}

	/**
	 *
	 * @param CMDSTR
	 */

	public static CMD_55AA disassemble(String CMDSTR) {

		if (CMDSTR == null || CMDSTR.length() < 9 || CMDSTR.length() % 2 == 1)
			return null;
		CMDSTR = CMDSTR.toUpperCase();
		CMD_55AA cmd = new CMD_55AA();
		if (CMDSTR.substring(0, 4).equals(STX)) {
			cmd.RSCTL = CMDSTR.substring(4, 6);
			cmd.LEN = CMDSTR.substring(6, 10);
			cmd.CMD = CMDSTR.substring(10, 12);
			cmd.DATA = CMDSTR.substring(12, CMDSTR.length() - 2);
			cmd.BCC = CMDSTR.substring(CMDSTR.length() - 2, CMDSTR.length());
			cmd.CMDSTR = CMDSTR;

			if (cmd.DATA.length() / 2 == Integer.parseInt(cmd.LEN, 16)) {
				String yh = EncodingUtil.addzero(EncodingUtil.yihuo(EncodingUtil.change(cmd.RSCTL
						+ cmd.LEN + cmd.CMD + cmd.DATA)), 1);
				if (yh.equalsIgnoreCase(cmd.BCC)) {
					return cmd;
				} else {
					return null;
				}
			} else {
				return null;
			}
		}
		return null;
	}

	/**
	 * 获取整条报文
	 * @return
	 */
	public String getCMDSTR() {
		return CMDSTR;
	}

	/**
	 * 获取帧序列号
	 * @return
	 */
	public String getRSCTL() {
		return RSCTL;
	}

	/**
	 * 获取内容长度
	 * @return
	 */
	public String getLEN() {
		return LEN;
	}

	/**
	 * 获取命令�?
	 * @return
	 */
	public String getCMD() {
		return CMD;
	}

	/**
	 * 获取内容
	 * @return
	 */
	public String getDATA() {
		return DATA;
	}

	/**
	 * 获取异或校验
	 * @return
	 */
	public String getBCC() {
		return BCC;
	}

}
